package com.xxgc.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.ConnectException;

/**
 * 消息队列相关配置
 */
@Configuration
public class RabbitMQConfig {

    //交换机的名称
    private final String EXCHANGE_NAME = "my_exchange";
    //队列的名字
    private final String QUEUE_NAME = "my_queue";

    /**
     * 创建交换机
     * @return
     */
    @Bean("iocExchange")
    public Exchange getExchange(){
        return ExchangeBuilder
                .topicExchange(EXCHANGE_NAME)
                //是否持久化
                .durable(true)
                .build();
    }

    /**
     * 创建队列
     * @return
     */
    @Bean("iocQueue")
    public Queue getMessageQueue(){
        return QueueBuilder
                .durable(QUEUE_NAME)
                .ttl(2000)//队列中所有值过期时间2秒
                .build();
    }

    /**
     * 交换机和队列绑定
     * @param exchange
     * @param queue
     * @return
     */
    @Bean
    public Binding bindingExchangeQueue(@Qualifier("iocExchange") Exchange exchange,
                                        @Qualifier("iocQueue") Queue queue){
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("#.wllxy.#")
                .noargs();
    }

    /**
     *监听mq的回调函数
     * @param connectionFactory
     * @return
     */
    @Bean
    public RabbitTemplate creatRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        //连接工程添加链接
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //是否强制调用回调函数
        rabbitTemplate.setMandatory(true);
        //回调方法
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData 相关配置信息
             * @param b 是否成功收到
             * @param s 失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (b){
                    System.out.println("交换机已收到并成功添加到队列中");
                }else {
                    System.out.println("失败了："+s);
                    System.out.println("配置信息："+correlationData);
                }
            }
        });
        return rabbitTemplate;
    }
}
